package controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import dao.SchoolDaoImpl;
import entity.School;
import exception.BaseException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;

public class SchoolReadCtl extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        JSONObject message = new JSONObject();
        String id_str = request.getParameter("id");
        try {
            Long id_long = Long.parseLong(id_str);
//          School school = ServiceFactory.getService(SchoolDaoInterface.class,"SchoolDaoImpl").find(id_long);
            School school = SchoolDaoImpl.getInstance().find(id_long);
            String school_json = JSON.toJSONString(school, JSONWriter.Feature.ReferenceDetection);
            response.getWriter().println(school_json);
        } catch (BaseException e) {
            message.put("message", e.getMessage());
            response.getWriter().println(message);
            e.printStackTrace();
        } catch (SQLException e) {
            message.put("message", "数据库操作异常");
            response.getWriter().println(message);
            e.printStackTrace();
        } catch(Exception e) {
            message.put("message", "网络异常");
            response.getWriter().println(message);
            e.printStackTrace();
        }
    }


    protected void doPut(HttpServletRequest request, HttpServletResponse response)
            throws  IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        JSONObject message = new JSONObject();
        try {
            Collection<School> schoolList = SchoolDaoImpl.getInstance().findAll();
            String schools_json = JSON.toJSONString(schoolList, JSONWriter.Feature.ReferenceDetection);
            response.getWriter().println(schools_json);
        } catch (BaseException e) {
            message.put("message", e.getMessage());
            response.getWriter().println(message);
            e.printStackTrace();
        } catch (SQLException e) {
            message.put("message", "数据库操作异常");
            response.getWriter().println(message);
            e.printStackTrace();
        } catch(Exception e) {
            message.put("message", "网络异常");
            response.getWriter().println(message);
            e.printStackTrace();
        }
    }
}